package com.haidechizi.mybatis.demo.service;

import com.haidechizi.mybatis.demo.dao.LogDao;
import com.haidechizi.mybatis.demo.entity.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Slf4j
@Service
public class LogService {

    @Autowired
    private LogDao logDao;

    @Transactional
    public void insertLog(Log log) {
        logDao.insertLog(log);
        // 模拟发生异常
        if (log.getId() != null) {
            throw new RuntimeException("模拟异常");
        }
    }

    @Transactional
    public void insertLog1(Log log) {
        try {
            logDao.insertLog(log);
            // 模拟发生异常
            if (log.getId() != null) {
                throw new RuntimeException("模拟异常");
            }
        } catch (Exception e) {
            LogService.log.warn("保存日志出现异常", e);
        }

    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insertLog2(Log log) {
        logDao.insertLog(log);
        // 模拟发生异常
        if (log.getId() != null) {
            throw new RuntimeException("模拟异常");
        }
    }
}
